from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from ..core.database import get_db
from ..models.product import Product
from ..models.store import Store
from ..models.group_buy_order import GroupBuyOrder

router = APIRouter(prefix="/api", tags=["products"])

@router.get("/banners")
async def get_banners(db: Session = Depends(get_db)):
    """获取首页轮播图数据"""
    try:
        # 获取推荐商品作为banner
        # 这里可以根据业务需求调整筛选条件，比如按销量、评分等
        products = db.query(Product).filter(Product.status == 1).limit(5).all()
        
        banners = []
        for product in products:
            # 获取店铺信息
            store = db.query(Store).filter(Store.id == product.store_id).first()
            if not store:
                continue
                
            # 获取拼购信息（优先获取进行中的，如果没有则获取最新的）
            group_buy = db.query(GroupBuyOrder).filter(
                GroupBuyOrder.product_id == product.id,
                GroupBuyOrder.status == 1  # 拼购中
            ).first()
            
            if not group_buy:
                # 如果没有进行中的拼购，获取最新的拼购信息
                group_buy = db.query(GroupBuyOrder).filter(
                    GroupBuyOrder.product_id == product.id
                ).order_by(GroupBuyOrder.id.desc()).first()
                
            if not group_buy:
                continue
                
            # 计算折扣
            discount = 0
            if product.original_price and product.original_price > 0:
                discount = round((product.group_buy_price / product.original_price) * 10, 1)
            
            # 处理图片
            images = product.images if isinstance(product.images, list) else [img.strip() for img in product.images.split(',') if product.images and img.strip()]
            
            banners.append({
                "id": product.id,
                "image": images[0] if images and len(images) > 0 else "",
                "title": product.name,
                "subtitle": f"{store.name} - {product.description[:30] if product.description else ''}",
                "price": f"¥{product.group_buy_price}",
                "originalPrice": f"¥{product.original_price}",
                "productId": product.id
            })
        
        return banners
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取banner失败: {str(e)}")

@router.get("/products")
async def get_products(db: Session = Depends(get_db)):
    """获取推荐商品列表"""
    try:
        # 获取上架的商品
        products = db.query(Product).filter(Product.status == 1).all()
        
        result = []
        for product in products:
            # 获取店铺信息
            store = db.query(Store).filter(Store.id == product.store_id).first()
            if not store:
                continue
                
            # 获取拼购信息（优先获取进行中的，如果没有则获取最新的）
            group_buy = db.query(GroupBuyOrder).filter(
                GroupBuyOrder.product_id == product.id,
                GroupBuyOrder.status == 1  # 拼购中
            ).first()
            
            if not group_buy:
                # 如果没有进行中的拼购，获取最新的拼购信息
                group_buy = db.query(GroupBuyOrder).filter(
                    GroupBuyOrder.product_id == product.id
                ).order_by(GroupBuyOrder.id.desc()).first()
                
            if not group_buy:
                continue
                
            # 计算进度百分比
            progress = 0
            if group_buy.total_shares > 0:
                progress = round((group_buy.sold_shares / group_buy.total_shares) * 100)
            
            # 处理图片
            images = product.images if isinstance(product.images, list) else [img.strip() for img in product.images.split(',') if product.images and img.strip()]
            
            result.append({
                "id": product.id,
                "name": product.name,
                "image": images[0] if images and len(images) > 0 else "",
                "originalPrice": float(product.original_price) if product.original_price else 0,
                "groupBuyPrice": float(product.group_buy_price) if product.group_buy_price else 0,
                "soldShares": group_buy.sold_shares,
                "totalShares": group_buy.total_shares,
                "progress": progress
            })
        
        return result
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取商品列表失败: {str(e)}")

@router.get("/product/{product_id}")
async def get_product_detail(product_id: int, db: Session = Depends(get_db)):
    """获取商品详情"""
    try:
        # 获取商品信息
        product = db.query(Product).filter(Product.id == product_id).first()
        if not product:
            raise HTTPException(status_code=404, detail="商品不存在")
            
        # 获取店铺信息
        store = db.query(Store).filter(Store.id == product.store_id).first()
        if not store:
            raise HTTPException(status_code=404, detail="店铺不存在")
            
        # 获取拼购信息（优先获取进行中的，如果没有则获取最新的）
        group_buy = db.query(GroupBuyOrder).filter(
            GroupBuyOrder.product_id == product.id,
            GroupBuyOrder.status == 1  # 拼购中
        ).first()
        
        if not group_buy:
            # 如果没有进行中的拼购，获取最新的拼购信息
            group_buy = db.query(GroupBuyOrder).filter(
                GroupBuyOrder.product_id == product.id
            ).order_by(GroupBuyOrder.id.desc()).first()
            
        if not group_buy:
            raise HTTPException(status_code=404, detail="拼购活动不存在")
            
        # 计算折扣
        discount = 0
        if product.original_price and product.original_price > 0:
            discount = round((product.group_buy_price / product.original_price) * 10, 1)
        
        # 处理图片字段
        images = product.images if isinstance(product.images, list) else [img.strip() for img in product.images.split(',') if product.images and img.strip()]
        
        return {
            "id": product.id,
            "name": product.name,
            "images": images,
            "originalPrice": float(product.original_price) if product.original_price else 0,
            "groupBuyPrice": float(product.group_buy_price) if product.group_buy_price else 0,
            "discount": discount,
            "storeName": store.name,
            "description": product.description or "",
            "groupBuy": {
                "id": group_buy.id,
                "soldShares": group_buy.sold_shares,
                "totalShares": group_buy.total_shares,
                "startTime": group_buy.start_time,
                "duration": 24 * 60 * 60 * 1000  # 24小时，单位毫秒
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取商品详情失败: {str(e)}") 